package session

import (
	"sync"
)

type MemorySession struct {
	data    map[string]interface{}
	id      string
	rwMutex sync.RWMutex
	flag    int
}

func NewMemorySession(id string) *MemorySession {
	return &MemorySession{
		data:    make(map[string]interface{}, 8),
		id:      id,
		rwMutex: sync.RWMutex{},
		flag:    0,
	}
}

func (m *MemorySession)GetId() string {
	return m.id
}

func (m *MemorySession) IsModify() bool {
	return m.flag == sessionFlagModify
}

func (m *MemorySession) Set(key string, value interface{}) error {
	m.rwMutex.Lock()
	defer m.rwMutex.Unlock()
	m.data[key] = value
	return nil
}

func (m *MemorySession) Save() (err error) {
	return
}

func (m *MemorySession) Get(key string) (value interface{}, err error) {
	m.rwMutex.RLock()
	defer m.rwMutex.Unlock()
	value, ok := m.data[key]
	if !ok {
		err = ErrSessionKeyNotExist
	}
	return
}

func (m *MemorySession) Del(key string) error {
	m.rwMutex.Lock()
	defer m.rwMutex.Unlock()
	delete(m.data, key)
	return nil
}
